package com.kld.shop.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.page.PageInfoResult;
import com.kld.common.util.DateUtil;
import com.kld.common.util.EncryptionUtil;
import com.kld.shop.controller.base.BaseController;
import com.kld.sys.api.ISysApprovalService;
import com.kld.sys.api.ISysOrgUnitService;
import com.kld.sys.api.ISysUserService;
import com.kld.sys.po.SysOrgUnit;
import com.kld.sys.po.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Dan on 2015/7/30.
 */
@Controller
@RequestMapping("/admin/sysUser")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysApprovalService sysApprovalService;
    @Resource
    private ISysOrgUnitService sysOrgUnitService;

    @RequestMapping("userList")
    public String userList(){
        return "admin/user/userList";
    }
    @RequestMapping("/userApprovalList")
    public String approvalUserList(){
        return "admin/user/userApprovalList";
    }
    @ResponseBody()
    @RequestMapping("/getUserList")
    public ResultMsg getUserList(){
        ResultMsg rmsg = new ResultMsg();
        PageHelper pageHelper = new PageHelper();
        Map<String,Object> map = new HashMap<String,Object>();
        String oucode = request.getParameter("oucode");
        if(StringUtils.isBlank(oucode)){
            oucode = getUserOuCode();
        }
        if(StringUtils.isNotBlank(oucode)){
            SysOrgUnit sys_orgunit = sysOrgUnitService.getSysOrgunitByOuCode(oucode);
            if(sys_orgunit.getOulevel().intValue()>1){
                map.put("oucode",oucode);
            }
        }
        map.put("nostate", -1);
        try {
            rmsg = sysUserService.getSysUserList(map, getPageNum(), getPageSize());
        }catch (Exception ex){
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }

    /**
     * 创建账户
     * @creator niudan
     * @param user
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "createUser", method = RequestMethod.POST)
    public ResultMsg createUser(SysUser user){
        ResultMsg rmsg = new ResultMsg();
        SysUser oldUser = sysUserService.getUserByUserName(user.getUsername());
        if (oldUser!=null ){

            rmsg.setResult(false);
            rmsg.setMsg("该操作员已经存在!");
            return  rmsg;
        }
        user.setState(0);
        //设置初始化密码
        if(StringUtils.isBlank(user.getPwd())){
            user.setPwd(EncryptionUtil.MD5("111111").toLowerCase());
        }
        user.setCreatetime(DateUtil.getDate());
        user.setCreator(getUserName());
        try {
            rmsg = sysUserService.insertWithTrans(user);
        } catch (Exception e) {
            logger.info("创建新用户失败", e);
            rmsg.setResult(false);
            rmsg.setMsg("创建新帐户失败"+e.getMessage());
        }
        response.setContentType("text/html");
        return rmsg;
    }

    /**
     * 编辑用户信息
     * @param user
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "editUser", method = RequestMethod.POST )
    public ResultMsg editUser(SysUser user){
        ResultMsg rmsg = new ResultMsg();
        response.setContentType("text/html");
        SysUser newUser = sysUserService.getUserByUserName(user.getUsername());

        //判断账户是否存在
        if(newUser==null){
            rmsg.setResult(false);
            rmsg.setMsg("编辑失败，用户不存在");
            return rmsg;
        }
        if(newUser.getState()==1){
            if(!user.getRolecode().equals(newUser.getRolecode())){
                newUser.setState(0);
            }
        }else{
            newUser.setState(0);
        }
//        newUser.setEmail(user.getEmail());
        newUser.setGender(user.getGender());
        newUser.setMobile(user.getMobile());
        newUser.setModifier(getUserName());
        newUser.setModitime(DateUtil.getDate());
//        newUser.setOucode(user.getOucode());
        newUser.setRealname(user.getRealname());
        newUser.setRolecode(user.getRolecode());
        newUser.setPhone(user.getPhone());
        newUser.setJob(user.getJob());
            try {
            //更新账户信息
            int upd = sysUserService.update(newUser);
            if(upd>0){
                rmsg.setResult(true);
                rmsg.setMsg("编辑成功！");
            }else {
                rmsg.setResult(false);
                rmsg.setMsg("编辑失败！");
            }
        } catch (Exception e) {
                logger.info("编辑用户失败",e);
            rmsg.setResult(false);
            rmsg.setMsg("编辑失败！"+e.getMessage());
        }
        return rmsg;
    }

    /**
     * 删除用户信息
     * @param username 用户名
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "deleteUser", method = RequestMethod.POST)
    public ResultMsg deleteUser(String username){
        ResultMsg rmsg = new ResultMsg();

        SysUser user = sysUserService.getUserByUserName(username);
        //判断账户是否存在
        if(user==null){
            rmsg.setResult(false);
            rmsg.setMsg("删除失败，用户不存在");
            return rmsg;
        }

        try {
            //逻辑删除账户信息;
            user.setState(-1);
            int del = sysUserService.update(user);
            if(del>0){
                rmsg.setResult(true);
                rmsg.setMsg("删除操作成功！");
            }else {
                rmsg.setResult(false);
                rmsg.setMsg("操作失败！");
            }
        } catch (Exception e) {
            logger.info("删除用户失败",e);
            rmsg.setResult(false);
            rmsg.setMsg("操作失败！"+e.getMessage());
        }
        return rmsg;
    }
    @ResponseBody()
    @RequestMapping("/getApprovalUserList")
    public ResultMsg getApprovalUserList(){
        ResultMsg resultMsg=null;
        resultMsg = sysUserService.getApprovalUserList(getPageNum(), getPageSize());
        return resultMsg;
    }

    @ResponseBody()
    @RequestMapping("/approvalUser")
    public ResultMsg ApprovalUser(){
        ResultMsg result=new ResultMsg();
        HashMap<String,Object> map1=new HashMap<String, Object>();
        String userid = getUserName();
        String oucode = getUserOuCode();
        String usernames=request.getParameter("usernames");
        String opinion=request.getParameter("opinion");
        String state=request.getParameter("state");
        String[] usernameList = usernames.split(",");
        int a=0;
        for(String username:usernameList){
            SysUser sys_user=new SysUser();
            sys_user.setUsername(username);
            sys_user.setState(Integer.parseInt(state));
            map1.put("bsnsid",username);
            map1.put("approvetype",2);
            map1.put("state",state);
            map1.put("approver",userid);
            map1.put("approvetime",new Date());
            map1.put("orgid", oucode);
            map1.put("opinion", opinion);
            a=sysUserService.updateAppBatch(sys_user,map1);
        }
        if(a>0){
            result.setResult(true);
            result.setMsg("审核成功");
        }else {
            result.setResult(false);
            result.setMsg("审核失败");
        }
        return result;
    }
}
